package com.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gulimall.cart.feign.ProductFeignService;
import com.gulimall.cart.interceptor.CartInterceptor;
import com.gulimall.cart.service.CartService;
import com.gulimall.cart.vo.Cart;
import com.gulimall.cart.vo.CartItem;
import com.gulimall.cart.vo.SkuInfoVo;
import com.gulimall.cart.vo.UserInfoTo;
import com.sunhao.common.constant.CartConstant;
import com.sunhao.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * 描述：CartServiceImpl 类的用途
 * 日期：2025/1/18
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();


        String res = (String) cartOps.get(skuId.toString());

        if (StringUtils.isEmpty(res))
        {
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1.远程调用查询商品信息
                R info = productFeignService.info(skuId);
                //购物车的一个购物项
                SkuInfoVo data = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });

                //2.商品信息添加到购物车

                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(data.getPrice());
            },executor);

            //3.远程查询sku的组合信息
            CompletableFuture<Void> getSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            }, executor);

            //等待两个线程执行完成
            CompletableFuture.allOf(getSkuInfoTask, getSaleAttrValues).get();

            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(),s);
            return cartItem;
        }
        else
        {
            CartItem cartItem = new CartItem();
            CartItem item = JSON.parseObject(res, CartItem.class);
            item.setCount(cartItem.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(item));
            return cartItem;
        }


    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(str, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null )
        {
            //已登录
            String cartKey = CART_PREFIX+userInfoTo.getUserId();
            //获取未登录购物车的商品 并添加到已登录的购物车
            List<CartItem> cartItems = getCartItems(CART_PREFIX + userInfoTo.getUserKey());
            for (CartItem cartItem : cartItems) {
                 addToCart(cartItem.getSkuId(), cartItem.getCount());
            }

            //清空临时购物车的数据
            clearCart(CART_PREFIX + userInfoTo.getUserKey());

            List<CartItem> items = getCartItems(cartKey);
            cart.setItems(items);
        }
        else {
            //未登录
            String userKey = userInfoTo.getUserKey();
            String cartKey = CART_PREFIX + userKey;
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer checked) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem item = getCartItem(skuId);
        item.setCheck(checked==1?true:false);
        String s = JSON.toJSONString(item);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        CartItem item = getCartItem(skuId);
        item.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(item));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    /**
     * 获取到要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null)
        {
            cartKey = CART_PREFIX+userInfoTo.getUserId();
        }
        else
        {
            cartKey = CART_PREFIX+userInfoTo.getUserKey();
        }

        //所有对redis的增删改查，都是针对cartKey的增删改查
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);

        return operations;
    }

    private List<CartItem> getCartItems(String cartKey)
    {
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        if (values != null && values.size() > 0)
        {
            List<CartItem> collect = values.stream().map(obj -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());

           return collect;
        }
        return null;
    }
}
